<template>
  <section
    v-loading="loading"
    class="new-article"
    element-loading-text="拼命加载中"
  >
    <header>
      <div class="tilte">
        <el-input v-model="article.title" placeholder="请输入文章标题" />
      </div>
      <div class="ctrl-panel">
        <span v-if="articleLoading" class="articleLoading btn-item">
          <i class="el-icon-loading" />
        </span>
        <nuxt-link to="/tempArticle" class="btn-temp btn-item">
          草稿箱
        </nuxt-link>
        <span
          class="el-icon-picture-outline btn-upload-article-cover btn-item"
          @click="isShowDialog_uploadArticleCover = true"
        />
        <el-button
          type="primary"
          size="small"
          class="btn-item"
          @click="isShowDialog_uploadArticle = true"
        >
          发布
        </el-button>
      </div>
    </header>
    <mavon-editor :md-str="article.content" @saveMd="saveMd" />

    <el-dialog
      title="发布博客"
      :visible.sync="isShowDialog_uploadArticle"
      width="400px"
    >
      <publish-article
        :article-id="article.articleId"
        :article-tags="article.tags"
        :article-type-id="article.articleTypeId"
        @publishArticle="publishArticle"
        @mergeArticleData="mergeArticleData"
      />
    </el-dialog>

    <el-dialog
      title="添加封面图"
      :visible.sync="isShowDialog_uploadArticleCover"
      width="540px"
    >
      <croppa-artcle-cover
        :initial-image="article.articleImg"
        :article-id="article.articleId"
        @onClose="isShowDialog_uploadArticleCover = false"
      />
    </el-dialog>
  </section>
</template>

<script>
// 引入工具
import { dateFormat } from '~/assets/js/util'
// 引入组件
import MavonEditor from '~/components/article/MavonEditor'
import CroppaArtcleCover from '~/components/article/CroppaArtcleCover'
import PublishArticle from '~/components/article/PublishArticle'

export default {
  middleware: 'isSignIn',
  layout: 'fullScreen',
  head() {
    return {
      title: '编辑'
    }
  },
  components: {
    MavonEditor,
    CroppaArtcleCover,
    PublishArticle
  },
  data() {
    return {
      isShowDialog_uploadArticle: false,
      isShowDialog_uploadArticleCover: false,
      article: {
        title: '',
        articleImg: '',
        content: '',
        tags: [],
        tagIds: [],
        articleTypeId: '',
        status: 'TEMP',
        articleId: ''
      },
      demoTags: [],
      inputVisible: false,
      inputValue: '',
      loading: false,
      articleLoading: false
    }
  },
  // async asyncData({ params, $axios }) {
  //   if (params.id) {
  //     try {
  //       const { status, msg, data } = await $axios.$get('/api/article/get/' + params.id)
  //       if (status === 200) {
  //         const oldArticle = {}
  //         oldArticle.title = data.title
  //         oldArticle.articleImg = data.articleImg
  //         oldArticle.content = data.content
  //         oldArticle.tags = data.tags
  //         oldArticle.articleTypeId = data.articleTypeId
  //         oldArticle.status = data.status
  //         oldArticle.articleId = data.id
  //         return { article: oldArticle }
  //       } else {
  //         this.$message.error(msg)
  //       }
  //     } catch (e) {
  //       console.log(e)
  //     }
  //   }
  // },
  computed: {
    userData() {
      return this.$store.state.user.userData
    }
  },
  async mounted() {
    if (!this.$route.params.id) { // 新建文章
      try {
        const tempArticle = JSON.parse(JSON.stringify(this.article))
        tempArticle.title = dateFormat('yyyy-MM-dd HH:mm:ss')
        // 创建临时文章
        const res2 = await this.$axios.$post('/api/article/upload', tempArticle, {
          headers: {
            YDSY_HEADER_TOKEN: this.userData && this.userData.userToken
          }
        })
        if (res2.status === 200) {
          this.article.articleId = res2.data
          this.$message.info('已保存为草稿')
        } else {
          this.$message.error(res2.msg)
        }
      } catch (e) {
        console.log(e)
      }
    } else if (this.$route.params.id) { // 更新文章，获取文章
      try {
        this.loading = true
        const { status, msg, data } = await this.$axios.$get('/api/article/get/' + this.$route.params.id)
        this.loading = false
        if (status === 200) {
          // console.log(data)
          const oldArticle = {}
          oldArticle.title = data.title
          oldArticle.articleImg = data.articleImg
          oldArticle.content = data.content
          oldArticle.tags = data.tags
          oldArticle.articleTypeId = data.articleTypeId
          oldArticle.status = data.status
          oldArticle.articleId = data.id

          Object.assign(this.article, oldArticle)
        } else {
          this.$message.error(msg)
        }
      } catch (e) {
        console.log(e)
      }
    }
  },
  methods: {
    saveMd(mdStr) {
      // console.log('str', mdStr)
      // console.log('xssStr', this.$xss(mdStr))
      // 更新临时文章
      this.article.content = mdStr
      const tempArticle = {
        'content': mdStr.trim()
      }
      this.updateArticle(tempArticle)
    },
    async updateArticle(newArticle, publish = false) {
      const params = {
        'articleId': this.article.articleId,
        'content': this.article.content.trim(),
        'status': 'TEMP',
        'title': this.article.title.trim()
      }
      Object.assign(params, newArticle)
      this.articleLoading = true
      // 更新文章
      const data = await this.$request({
        context: this,
        method: 'post',
        url: 'article/update',
        params
      })
      this.articleLoading = false
      if (!data) return
      if (publish) {
        this.isShowDialog_uploadArticle = false
        this.$router.push('/article/' + this.article.articleId)
      }
    },
    mergeArticleData(data) {
      Object.assign(this.article, data)
    },
    publishArticle() {
      // 发布文章

      const newArticle = {
        'status': 'FINISH'
      }
      if (this.article.title.trim() === '') {
        this.$message.info('标题不能为空')
        this.isShowDialog_uploadArticle = false
        return
      } else if (this.article.content.trim() === '') {
        this.$message.info('正文不能为空')
        this.isShowDialog_uploadArticle = false
        return
      } else if (this.article.articleTypeId === '') {
        this.$message.info('请选择分类')
        return
      }
      this.updateArticle(newArticle, true)
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/css/public";
.new-article {
  width: 100%;
  header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 70px;
    border-bottom: 0px solid $theme-color-border;

    .tilte {
      flex: 1;

      /deep/ .el-input {
        .el-input__inner {
          height: 60px;
          line-height: 60px;
          font-size: 26px;
          font-weight: 700;

          &,&:focus {
            border: none;
          }
        }
      }
    }

    .ctrl-panel {
      display: flex;
      justify-content: space-between;
      align-items: center;
      span.articleLoading {
        font-size: 30px;
        color: $theme-color;
      }

      .btn-item {
        margin: 0 20px;
      }
      .btn-temp {
        color: $theme-color;
      }
      .btn-upload-article-cover {
        cursor: pointer;
        color: $theme-color;
        font-size: 20px;
        margin: 0 20px;
      }
    }
  }
}
</style>
